package es

import (
	"C/models/mysql"
	"C/shenzhousrv"
	"bytes"
	"context"
	"encoding/json"
	"github.com/elastic/go-elasticsearch/v7/esapi"
	"log"
	"strconv"
	"sync"
)

// SyncGoods 同步商品到es
func SyncGoods(goods []mysql.Goods) {
	var wg sync.WaitGroup
	for _, good := range goods {
		wg.Add(1)

		go func(goods mysql.Goods) {
			defer wg.Done()

			// Build the request body.
			data, err := json.Marshal(good)
			if err != nil {
				log.Fatalf("Error marshaling document: %s", err)
			}

			// Set up the request object.
			req := esapi.IndexRequest{
				Index:      "goods",
				DocumentID: strconv.Itoa(int(good.ID)),
				Body:       bytes.NewReader(data),
				Refresh:    "true",
			}

			// Perform the request with the client.
			res, err := req.Do(context.Background(), Es)
			if err != nil {
				log.Fatalf("Error getting response: %s", err)
			}
			defer res.Body.Close()

		}(good)
	}
	wg.Wait()
}

// GoodsSearch es商品搜索
func GoodsSearch(KeyWord string) (goodsList []*shenzhousrv.GoodsList, err error) {
	var buf bytes.Buffer
	query := map[string]interface{}{}
	if KeyWord != "" {
		query = map[string]interface{}{
			"query": map[string]interface{}{
				"match": map[string]interface{}{
					"title": KeyWord,
				},
			},
		}
	} else {
		query = map[string]interface{}{
			"query": map[string]interface{}{
				"match_all": map[string]interface{}{},
			},
		}
	}
	json.NewEncoder(&buf).Encode(query)
	res, err := Es.Search(
		Es.Search.WithContext(context.Background()),
		Es.Search.WithIndex("goods"),
		Es.Search.WithBody(&buf),
		Es.Search.WithTrackTotalHits(true),
		Es.Search.WithPretty(),
	)
	if err != nil {
		log.Fatalf("Error getting response: %s", err)
	}
	defer res.Body.Close()
	var r map[string]interface{}
	json.NewDecoder(res.Body).Decode(&r)
	for _, hit := range r["hits"].(map[string]interface{})["hits"].([]interface{}) {
		xx := hit.(map[string]interface{})["_source"].(map[string]interface{})

		goodsList = append(goodsList, &shenzhousrv.GoodsList{
			GoodsId: int64(xx["ID"].(float64)),
			Title:   xx["title"].(string),
			Cover:   xx["cover"].(string),
			Price:   float32(xx["price"].(float64)),
			Likes:   int64(xx["likes"].(float64)),
			Stock:   int64(xx["stock"].(float64)),
		})
	}
	return
}
